import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  Select,
  Cascader,
  Divider,
  Badge,
  Button,
  Table,
  Modal,
  Tooltip,
  Dropdown,
  Menu,
  message,
} from 'antd';
import { DownOutlined } from '@ant-design/icons';

import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { Item } = Form;
const statusVal: any = ['error', 'success', 'error'];
const statusTxt = ['调试中', '运营中', '已删除'];

const { pathname } = window.location;

interface BoxManagementListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: any;
  gardenList: any;
  bluetooth: string[];
  firmware: string[];
  INITINFO: any;
  location: { query: any };
  screen: string;
  hasPath: string;
}

interface BoxManagementListState {
  searchValues: any;
  statusVisible: boolean;
  statusId: number;
  pageIndex:number;
  pageSize:number;
  rowId:number;
}

@connect(
  ({
    boxManagementList: {
      dataInfo, gardenList, bluetooth, firmware,
    },
    common: { INITINFO },
    global: { screen, hasPath },
    loading,
  }: any) => ({
    dataInfo,
    gardenList,
    bluetooth,
    firmware,
    INITINFO,
    screen,
    hasPath,
    loading: loading.effects['boxManagementList/fetch'],
  }),
)
class BoxManagementListElem extends React.Component<BoxManagementListProps,
BoxManagementListState> {
  columns: any = [
    {
      title: '编号',
      dataIndex: 'code',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '箱体名称',
      dataIndex: 'name',
      width: 120,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleEditbox(record.id, text)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      width: 64,
      render: (text: number) => (text === 1 ? '宝箱' : '宝盒'),
    },
    {
      title: '箱体套餐',
      dataIndex: 'tariffpkgName',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '驿站',
      dataIndex: 'posthouseName',
      width: 100,
      render: (text: string) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '结构版本',
      dataIndex: 'structVersion',
      width: 90,
    },
    {
      title: '蓝牙版本/名称',
      dataIndex: 'btLockVersion',
      width: 130,
      render: (text: string, row: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}/{row.bluetoothName}</div>
        </Tooltip>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (text: number) => <Badge status={statusVal[text - 1]} text={statusTxt[text - 1]} />,
    },
    {
      title: '待取件',
      dataIndex: 'unPickCount',
      width: 80,
      render: (text: number) => text || '--',
    },
    {
      title: '操作',
      dataIndex: 'id',
      fixed: 'right',
      width: 148,
      render: (text: number, record: any) => (
        <>
          <span className="operLink" onClick={() => this.handleEditbox(text, record.name)}>
            编辑
          </span>
          <Divider type="vertical" />
          <span className="operLink" onClick={() => this.handleChangeStatus(true, text)}>
            禁用
          </span>
          <Divider type="vertical" />
          <Dropdown arrow overlay={() => this.menu(record)}>
            <span className="operLink">
              更多 <DownOutlined />
            </span>
          </Dropdown>
        </>
      ),
    },
  ];

  state: BoxManagementListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    statusVisible: false,
    statusId: 0,
    rowId: 0,
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.handleValidation();
    this.fetchAction('fetchEdition');
    this.fetchAction('common/fetchAddressList');

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues } = this.state;
    const params = this.turnValuesType(searchValues);

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(params);
  };

  turnValuesType = (values: any) => {
    const {
      provinceCode,
      cityCode,
      countyCode,
      ...query
    } = values;
    return {
      ...query,
      areaCodes: [provinceCode, cityCode, countyCode].filter((item: any) => item),
    };
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  };

  menu = (record: any) => (
    <Menu>
      <Menu.Item
        className="operLink"
        onClick={() => this.fetchAction('downFile', record.id)}
      >
        下载二维码
      </Menu.Item>
      <Menu.Item
        className="operLink"
        onClick={() => message.warning('功能暂未开放！')}
      >
        箱体轨迹
      </Menu.Item>
    </Menu>
  );

  /**
   * 新建宝箱/宝盒
   */
  handleAddBox = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建宝箱/宝盒',
      url: '/basic/boxManagement/list/add',
    });
  };

  /**
   * 编辑宝箱/宝盒
   */
  handleEditbox = (id: number, name: string) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `编辑${name}`,
      url: `/basic/boxManagement/list/edit?id=${id}`,
    });
  };

  handleChangeStatus = (statusVisible: boolean, id: number = 0) => {
    this.setState({ statusVisible, statusId: id });
  };

  handleSureStatus = () => {
    const { searchValues: search, statusId: id } = this.state;
    const params = { search, id };
    this.fetchAction('changeStatus', params);
    this.handleChangeStatus(false);
  };

  handleValidation = () => {
    const { form: { getFieldValue } } = this.props;
    const value = getFieldValue('areaCodes');

    if (value.length) {
      const params = {
        pareaCode: value[0],
        careaCode: value[1],
        dareaCode: value[2],
      };
      this.fetchAction('fetchGarden', params);
    }
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { areaCodes = [], ...params } = values;
      const query: any = {
        ...params,
        pageIndex: 1,
        pageSize: 20,
      };

      if (areaCodes.length) {
        [query.provinceCode] = [areaCodes[0]];
        [query.cityCode] = [areaCodes[1]];
        [query.countyCode] = [areaCodes[2]];
      }

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '宝箱宝盒管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    this.fetchAction('clearGarden');

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '宝箱宝盒管理',
      url: pathname,
      isTopMenu: true,
    });
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '宝箱宝盒管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `boxManagementList/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const { pageIndex, pageSize, statusVisible } = this.state;
    const {
      form: { getFieldDecorator },
      dataInfo,
      gardenList,
      bluetooth,
      firmware,
      INITINFO: { addressList },
      loading,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.onSelectChange,
      onShowSizeChange: this.onSelectChange,
    };

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="　箱体名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　结构版本" colon={false}>
                  {getFieldDecorator('structVersion')(
                    <Select allowClear placeholder="请选择">
                      {firmware.map((item: string) => (
                        <Option value={item} key={item}>{item}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="蓝牙锁版本" colon={false}>
                  {getFieldDecorator('btLockVersio')(
                    <Select allowClear placeholder="请选择">
                      {bluetooth.map((item: string) => (
                        <Option value={item} key={item}>{item}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　箱体编号" colon={false}>
                  {getFieldDecorator('code')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="　　省市区" colon={false}>
                  {getFieldDecorator('areaCodes')(
                    <Cascader
                      changeOnSelect
                      options={addressList}
                      placeholder="请选择"
                    />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　小区/学校" colon={false}>
                  {getFieldDecorator('gardenId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      onFocus={this.handleValidation}
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {gardenList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={12} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleAddBox}
            >
              新建宝箱/宝盒
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1400 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          title="确认提示"
          visible={statusVisible}
          onOk={this.handleSureStatus}
          onCancel={() => this.handleChangeStatus(false)}
        >
          <p>确定禁用该箱体?</p>
        </Modal>
      </>
    );
  }
}

export default Form.create<BoxManagementListProps>()(BoxManagementListElem);
